package com.chainyoung.component_tmperson.ui.fragment;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import com.chainyoung.common.appcommon.entity.HdWallet;
import com.chainyoung.common.appcommon.hdwallet.ExchangeCalculator;
import com.chainyoung.component_tmperson.R;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;

public class WebTransactionSetGasFragment extends BottomSheetDialogFragment {


    private TextView btnCancel;
    private TextView btnConfirm;
    private TextView tvFee;
    private TextView tvFeeCacultor;
    private TextView tvGasPrice;
    private TextView tvGasLimit;
    private SeekBar seekBarGasPirce;
    private SeekBar seekBarGasLimit;


    private OptionListener onOptionListener;

    private BigDecimal gasPrice = BigDecimal.valueOf(3);//初始价格

    private BigDecimal actualGasPrice = gasPrice;

    private BigDecimal oriGasLimit = BigDecimal.valueOf(700000);//gaslimit

    private BigDecimal minGasLimit = BigDecimal.valueOf(21000);
    private BigDecimal maxGasLimit = BigDecimal.valueOf(7000000);
    private BigDecimal perGasLimit = BigDecimal.valueOf(69790);

    private BigDecimal actualGasLimit = oriGasLimit;


    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.tv_cancel) {
                if (onOptionListener != null) {
                    onOptionListener.onCancelJust(true);
                }
                dismiss();
            } else if (v.getId() == R.id.tv_confirm) {
                if (onOptionListener != null) {
                    onOptionListener.onConfirmAdjust(actualGasPrice, actualGasLimit);
                }

            }

        }
    };


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        final Activity parent = getActivity();
//        if (parent != null) {
//            onOptionListener = (OptionListener) parent;
//        } else {
//            onOptionListener = (OptionListener) context;
//        }
    }

    @Override
    public void onDetach() {
        if (onOptionListener != null) {
            onOptionListener.onCancelJust(false);
        }
        onOptionListener = null;
        super.onDetach();
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        BottomSheetDialog bottomSheetDialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_web_transaction_set_fragment, null);
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCancelable(false);
        bottomSheetDialog.setCanceledOnTouchOutside(false);
        btnCancel = view.findViewById(R.id.tv_cancel);
        btnConfirm = view.findViewById(R.id.tv_confirm);
        tvGasPrice = view.findViewById(R.id.tv_gas_price);
        tvGasLimit = view.findViewById(R.id.tv_gas_limit);
        seekBarGasPirce = view.findViewById(R.id.seekBar1);
        seekBarGasLimit = view.findViewById(R.id.seekBar2);
        tvFee = view.findViewById(R.id.tv_fee);
        tvFeeCacultor = view.findViewById(R.id.tv_fee_caculator);
        btnCancel.setOnClickListener(onClickListener);
        btnConfirm.setOnClickListener(onClickListener);


        try {
            Field mBehaviorField = bottomSheetDialog.getClass().getDeclaredField("mBehavior");
            mBehaviorField.setAccessible(true);
            final BottomSheetBehavior behavior = (BottomSheetBehavior) mBehaviorField.get(bottomSheetDialog);
            behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                @Override
                public void onStateChanged(@NonNull View bottomSheet, int newState) {
                    if (newState == BottomSheetBehavior.STATE_DRAGGING) {
                        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                    }
                }

                @Override
                public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                }
            });
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        setListener();

        updateView();

        return bottomSheetDialog;
    }


    private void setListener() {
        seekBarGasPirce.setMax(50);
        seekBarGasLimit.setMax(100);
        seekBarGasLimit.setProgress(Integer.valueOf(oriGasLimit.divide(perGasLimit, 0, RoundingMode.DOWN) + ""));
        setFee();


        seekBarGasPirce.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (progress == 0) {
                    actualGasPrice = gasPrice;
                } else {
                    actualGasPrice = gasPrice.multiply(new BigDecimal(progress));
                }

                tvGasPrice.setText(String.valueOf(actualGasPrice + "Gwei"));
                setFee();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        seekBarGasLimit.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (progress == 0) {
                    actualGasLimit = minGasLimit;
                } else if (progress == 100) {
                    actualGasLimit = maxGasLimit;
                } else {
                    actualGasLimit = perGasLimit.multiply(new BigDecimal(progress));
                }
                tvGasLimit.setText(actualGasLimit.setScale(0, RoundingMode.DOWN) + "");
                setFee();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    private void setFee() {
        tvFeeCacultor.setText(String.format("%s Gas Limit*%s Gas Price", actualGasLimit.setScale(0, RoundingMode.DOWN), actualGasPrice));
        BigDecimal bd = actualGasPrice.multiply(actualGasLimit).divide(ExchangeCalculator.ONE_GWEI, 8, RoundingMode.DOWN);
        tvFee.setText(String.valueOf(bd));
    }


    public void setData(BigDecimal origasPrice, BigDecimal actualGasPrice, BigDecimal gasLimit) {
        this.gasPrice = origasPrice;
        this.actualGasLimit = gasLimit;
        this.actualGasPrice = actualGasPrice;
        //updateView();
    }

    public void updateView() {

        seekBarGasPirce.setProgress(Integer.valueOf(actualGasPrice.divide(gasPrice, 0, RoundingMode.DOWN) + ""));
        seekBarGasLimit.setProgress(Integer.valueOf(actualGasLimit.divide(perGasLimit, 0, RoundingMode.DOWN) + ""));
        tvGasLimit.setText(actualGasLimit.setScale(0, RoundingMode.DOWN) + "");
        tvGasPrice.setText(String.valueOf(actualGasPrice + "Gwei"));
        setFee();

    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (isAdded()) {
            return;
        }
        super.show(manager, tag);
    }

    public interface OptionListener {

        void onCancelJust(boolean isNeedDismiss);

        void onConfirmAdjust(BigDecimal gasPrice, BigDecimal gasLimit);
    }

    public void setOnOptionListener(OptionListener onOptionListener) {
        this.onOptionListener = onOptionListener;
    }
}

